const express = require("express")
const router = express.Router()
const pool = require("../../db/db.js")
const Response = require("../../utils/ResponseData.js")

// 新增宠物接口
router.post("/add", (req, res, next) => {
    let { uid } = req.user
    let { p_img, p_name, p_year, p_gender, p_type, p_content, p_breed } = req.body
    const sql = "insert into pet (p_img, p_name, p_year, p_gender, p_type, p_content, p_breed ,user_id) values(?,?,?,?,?,?,?,?)"
    pool.query(sql, [p_img, p_name, p_year, p_gender, p_type, p_content, p_breed, uid], (err, result) => {
        if (err) {
            console.log("新增宠物错误", err);
            next(err)
            return
        }
        if (result && result.insertId > 0) {
            res.send(Response.success(null, "添加宠物成功"))
        } else {
            res.send(Response.error("添加宠物失败"))
        }
    })
})
//宠物列表获取
router.get("/getAll", (req, res, next) => {
    let { uid } = req.user
    const sql = "select * from pet where user_id=?"
    pool.querySync(sql, [uid])
        .then(result => {
            if (result && result.length > 0) {
                res.send(Response.success({ data: result, total: result.length }, "宠物列表查询成功"))
            } else {
                res.send(Response.error("宠物列表查询失败"))
            }
        }).catch(err => {
            if (err) {
                console.log("获取全部宠物失败", err);
                next(err)
                return
            }
        })

})
//
// 

module.exports = router